package com.kelvin.oocl.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.TreeSet;

import com.kelvin.oocl.comparator.CustomerBirthDateComparator;
import com.kelvin.oocl.comparator.CustomerIdComparator;
import com.kelvin.oocl.constart.Expression;
import com.kelvin.oocl.constart.SystemConstant;
import com.kelvin.oocl.operator.CustomerOperator;
import com.kelvin.oocl.operator.impl.CustomerOpetatorImpl;
import com.kelvin.oocl.pojo.Customer;
import com.kelvin.oocl.pojo.CustomerVo;
import com.kelvin.oocl.printer.FormatPrinter;
import com.kelvin.oocl.printer.FormatPrinterImpl;
import com.kelvin.oocl.processer.DataProcesser;
import com.kelvin.oocl.processer.impl.DataProcessorImpl;
import com.kelvin.oocl.scanner.DataScanner;
import com.kelvin.oocl.scanner.impl.DataScannerImpl;

public class DiapatcherImpl implements Dispatcher {
	private DataScanner scanner;
	private DataProcesser processer;
	private CustomerOperator operator;
	private FormatPrinter printer;
	private static String targetPath= "./src/main/java/customers.xml";
	
	public DiapatcherImpl() {
		this.scanner = new DataScannerImpl();
		this.processer = new DataProcessorImpl();
		this.operator = new CustomerOpetatorImpl();
		this.printer = new FormatPrinterImpl();
	}

	@Override
	public void initDBData(File file) throws FileNotFoundException {
		List<CustomerVo> scann = scanner.scann(file);
		List<Customer> process = processer.process(scann);
		operator.addAll(process);
		TreeSet<Customer> sort = operator.sort(new CustomerIdComparator());
		for (Customer customer : sort) {
			System.out.println(customer);
		}
	}

	@Override
	public String dispatcher(String command) throws IOException {
		System.out.println(command);
		System.out.println(command.matches(Expression.COMMAND_FILTER));
		if(command.matches(Expression.COMMAND_FILTER)){
			String[] strs = command.split("\\s+");
			if(strs[0].equals("L")){//L
				if("xml".equals(strs[1])){
					TreeSet<Customer> customers = operator.sort(new CustomerIdComparator());
					return printer.print(customers, "xml");
				}else {
					TreeSet<Customer> customers = operator.sort(new CustomerBirthDateComparator());
					return printer.print(customers, "line");
				}
			}else if(strs[0].equals("C")) {//C
				TreeSet<Customer> customers = operator.sort(new CustomerIdComparator());
				return printer.createXmlFile(customers, new File(targetPath));
			}else {
				return SystemConstant.QUIT;
			}
		}else {
			return SystemConstant.WRONG_COMMAND;
		}
	}

}
